// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import CM from "../../lib/cache/CM";
import { monitor } from "../../lib/common/Decorator";
import Tool from "../../lib/common/Tool";
import MsgMgr from "../../lib/event/MsgMgr";
import UINode from "../../lib/ui/UINode";
import DUser, { LevelInfo } from "../cache/DUser";
import MsgEnum from "../common/MsgEnum";

const {ccclass, property} = cc._decorator;

@ccclass
export default class UILevel extends UINode {
    protected _isSwallowTouch: boolean = false;
    public step:number = 250;
    public itemDict:Map<string, cc.Node> = new Map();
    protected prefab(): string {
        return "prefab/ui/UILevel";
    }

    protected onEvtShow(): void {
        
        let width = 0;
        for (let i = 0; i < 20; i++) {
            let level = (i+1);
            let item = Tool.clone(this["item_demo"], this);
            item.active = true;
            item.x = item.width/2+Math.floor(i/2)*this.step;
            item.y = this["scrollview"].height/3-(i%2)*this.step;
            item["level"] = level;
            item["layout_star"].active = false;
            item["label_level"].getComponent(cc.Label).string = level;
            this["content"].addChild(item);
            width = Math.floor(i/2)*this.step+item.width;
            this.itemDict.set(level.toString(), item);
        }
        this["content"].width = width;

        //this.related("", "DUser", "levelInfo");
        
        this.on_levelInfo_change("levelInfo", null, CM.ins(CM).get(DUser).levelInfo);
    }

    @monitor("DUser/levelInfo") 
    on_levelInfo_change(attrName, oldVal, newVal:LevelInfo[]){
        let maxLevel = CM.ins(CM).get(DUser).maxLevel;
        for (let i = 0; i < newVal.length; i++) {
            let info:LevelInfo = newVal[i];
            this.setItemState(info, maxLevel);
        }
    }

    setItemState(info:LevelInfo,maxLevel:number) {
        let item = this.itemDict.get(info.level.toString());
        if (!item) { return; }
        let isOpen = info.level <= maxLevel;
        item.getComponent(cc.Button).enabled = isOpen;
        item["layout_star"].active = isOpen;
        item["spr_lock"].active = !isOpen;
        for (let j = 1; j <= 3; j++) {
            let star = item["layout_star"].getChildByName("star"+j);
            let isLight = info.score >= j;
            star.getChildByName("light").active = isLight;
        }
    }

    on_click_item_demo(button) {
        let level = button.node["level"];
        MsgMgr.emit(MsgEnum.ON_ENTER_LEVEL, level);
    }
}
